<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text">
    <button id="btn">发送</button>
    <button id="off">关闭连接</button>
    <div id="content"></div>
</body>

</html>
<script>
    let content = document.querySelector('#content')
    let ws = new WebSocket('wss://echo.websocket.org')
    ws.onopen = function () {
        content.innerHTML += '<p style="color:red">服务器连接成功</p>'
    }

    document.querySelector("#btn").onclick = function () {
        let str = document.querySelector('input').value
        content.innerHTML += `<p>您:${str}</p>`
        ws.send(str)
    }

    ws.onmessage = function (data) {
        content.innerHTML += `<p>复读机：${data.data}</p>`
    }
</script>